package com.deliveryservicesystem.presentation.desktop;

import com.deliveryservicesystem.app.exceptions.NoRowSelected;
import com.deliveryservicesystem.app.exceptions.OutputError;
import com.deliveryservicesystem.app.util.AppUtils;
import com.deliveryservicesystem.service.impl.GeneralServicesImpl;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * File Name: MatchDialog.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.presentation.desktop.addpanel
 * Author: Lance
 * Date: Jun 30, 2012
 * Editor:
 */
public class MatchDialog extends javax.swing.JDialog
{

    private static final long serialVersionUID = 1L;
    private TableRowSorter<TableModel> rowSorter;
    private GeneralServicesImpl generalServices = new GeneralServicesImpl();
    private TableModel tableModel;
    private Integer selectedId;
    private String procedureSql;
    public static final int RET_CANCEL = 0;
    public static final int RET_OK = 1;

    /**
     * Creates new form MatchDialog
     */
    public MatchDialog(java.awt.Frame parent, boolean modal, String procedureSql) throws SQLException
    {
        super(parent, modal);
        initComponents();
        this.procedureSql = procedureSql;
        ResultSet resultSet = generalServices.getTableDataFromProcedure(procedureSql);
        tableModel = GenericTableModel.resultSetToTableModel(resultSet);
        setTableDataFromProcedure(procedureSql);

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction()
        {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e)
            {
                doClose(RET_CANCEL);
            }
        });
    }

    public void setTableDataFromProcedure(String procedureSql) throws SQLException
    {
        ResultSet resultSet = generalServices.getTableDataFromProcedure(procedureSql);
        tableModel = GenericTableModel.resultSetToTableModel(resultSet);
        setTableModel();
    }

    private void setTableModel()
    {
        tblMain.setModel(tableModel);
        rowSorter = new TableRowSorter<>(tableModel);
        tblMain.setRowSorter(rowSorter);
    }

    public Integer getReturnStatus()
    {
        return selectedId;
    }

    public void doClose()
    {
        int selectedRow = tblMain.getSelectedRow();
        String values = "0";

        try
        {
            if (selectedRow == -1)
            {
                throw new NoRowSelected("Please select a row from the table to edit");
            }
            values = tableModel.getValueAt(selectedRow, 0).toString();
        }
        catch (NoRowSelected ex)
        {
            JOptionPane.showMessageDialog(null, "Please select a row");
        }
        selectedId = Integer.parseInt(values);
        setVisible(false);
        dispose();
    }

    private void filterTable(TableRowSorter<TableModel> sorter, String filterText)
    {
        if (!filterText.equals("Enter search value"))
        {
            try
            {
                sorter.setRowFilter(RowFilter.regexFilter(filterText));
            }
            catch (PatternSyntaxException pse)
            {
                JOptionPane.showMessageDialog(this.getParent(), "Bad regex pattern\nPlease filter again", "Bad regex pattern", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblMain = new javax.swing.JTable();
        txtSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(tblMain);

        txtSearch.setForeground(new java.awt.Color(204, 204, 204));
        txtSearch.setText("Enter search value");
        txtSearch.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtSearchCaretUpdate(evt);
            }
        });
        txtSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtSearchFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtSearchFocusLost(evt);
            }
        });

        btnSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/toolbarButtonGraphics/general/Find16.gif"))); // NOI18N
        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearch))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSearch)
                    .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(okButton);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        //doClose(RET_OK);
        doClose();
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        if (AppUtils.askExitConfirm() == JOptionPane.YES_OPTION)
        {
            doClose(RET_CANCEL);
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
               doClose(RET_CANCEL);       
    }//GEN-LAST:event_closeDialog

    private void txtSearchCaretUpdate(javax.swing.event.CaretEvent evt)//GEN-FIRST:event_txtSearchCaretUpdate
    {//GEN-HEADEREND:event_txtSearchCaretUpdate
        filterTable(rowSorter, txtSearch.getText().trim());
    }//GEN-LAST:event_txtSearchCaretUpdate

    private void txtSearchFocusGained(java.awt.event.FocusEvent evt)//GEN-FIRST:event_txtSearchFocusGained
    {//GEN-HEADEREND:event_txtSearchFocusGained
        if (txtSearch.getText().equals("Enter search value"))
        {
            txtSearch.setText(null);
            txtSearch.setForeground(new java.awt.Color(0, 0, 0));
        }
    }//GEN-LAST:event_txtSearchFocusGained

    private void txtSearchFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_txtSearchFocusLost
    {//GEN-HEADEREND:event_txtSearchFocusLost
        if (txtSearch.getText().equals(""))
        {
            txtSearch.setText("Enter search value");
            txtSearch.setForeground(new java.awt.Color(204, 204, 204));
        }
    }//GEN-LAST:event_txtSearchFocusLost

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSearchActionPerformed
    {//GEN-HEADEREND:event_btnSearchActionPerformed
        try
        {
            setTableDataFromProcedure(procedureSql);
        }
        catch (SQLException ex)
        {
            OutputError.toLog(ex);
            OutputError.toUser(ex);
        }
        filterTable(rowSorter, txtSearch.getText().trim());
    }//GEN-LAST:event_btnSearchActionPerformed

    private void doClose(int retStatus)
    {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton okButton;
    private javax.swing.JTable tblMain;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
    private int returnStatus = RET_CANCEL;
}
